<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="耳标编号" prop="earNumber">
        <el-input
          v-model="queryParams.earNumber"
          placeholder="请输入耳标编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="养殖户" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入养殖户"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['dgw:tagNumber:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['dgw:tagNumber:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['dgw:tagNumber:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['dgw:tagNumber:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['dgw:tagNumber:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5" :push="10">
        <span v-model="ESum" style="color: #ffffff; float: right" >总计智能耳标安装: {{ESum}}</span>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="5" :xs="24">
        <el-table v-loading="loading" height="700" :data="deptList"
                  @row-click="selectRow"
                  :row-style="rowStyle"
                  @selection-change="handleSelectionChange">
          <!--      <el-table-column label="养殖用户id" align="center" prop="userId" />-->
          <el-table-column label="乡镇(12)" align="center" prop="deptName"/>
          <el-table-column label="耳标使用数量" align="center" prop="earNumber"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="small "
                @click="getSum(scope.row)"

              >查看
              </el-button>
              <!--                    <el-button
                                    size="mini"
                                    type="text"
                                    icon="el-icon-delete"
                                    @click="handleDelete(scope.row)"
                                    v-hasPermi="['dgw:vaccine:remove']"
                                  >删除</el-button>-->
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="5">
        <el-table v-loading="loading" height="700" :data="deptNameList"
                  :row-style="rowStyleU"
                  @selection-change="handleSelectionChange">

          <el-table-column :label=label  align="center" prop="village"/>
          <el-table-column label="耳标使用数量" align="center" prop="earNumberSum"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                @click="ClickEar(scope.row)"
              >查看用户</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="14" :xs="24">
        <el-table v-loading="loading"  :data="tagNumberList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="耳标编号" align="center" prop="earNumber" width="120"/>
          <el-table-column label="养殖户" align="center" prop="name"/>
          <el-table-column label="用户手机号码" align="center" prop="phone" width="120"/>
          <el-table-column label="用标地" align="center" prop="deptName"/>
          <el-table-column label="牛装标时月龄" align="center" prop="isUse">
            <template slot-scope="scope">
          <span>
            {{ scope.row.isUse + '个月' }}
          </span>
            </template>
          </el-table-column>
          <el-table-column label="装标牛预出栏时间" align="center" prop="cowTime" width="120"/>
          <el-table-column label="投保id" align="center" prop="insuranceId">
            <template slot-scope="scope">
              <el-tag :type="scope.row.insuranceId==0?'info':''">
                {{ scope.row.insuranceId == 0 ? '未投保' : '已投保' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="贷款" align="center" prop="loans">
            <template slot-scope="scope">
              <el-tag :type="scope.row.loans==0?'info':'success'">
                {{ scope.row.loans == 0 ? '未贷款' : '已贷款' }}
              </el-tag>

            </template>
          </el-table-column>
          <!--      <el-table-column label="地区id" align="center" prop="deptId"/>-->
          <el-table-column label="是否报废" align="center" prop="scrap">
            <template slot-scope="scope">
              <el-tag :type="scope.row.scrap==1?'':'danger'">
                {{ scope.row.scrap == 1 ? '正常' : '已报废' }}
              </el-tag>
            </template>
          </el-table-column>
                <el-table-column label="耳标核销" align="center" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-edit"
                      @click="updateScrap(scope.row)"
                    >耳标核销
                    </el-button>
                  </template>
                </el-table-column>
          <el-table-column label="耳标替换" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="updateEarNumber(scope.row)"
              >耳标替换
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>


    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改耳标对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="耳标编号" prop="earNumber">
          <el-input v-model="form.earNumber" placeholder="请输入耳标编号" />
        </el-form-item>
        <el-form-item label="用户手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入用户手机号码" />
        </el-form-item>
        <el-form-item label="该字段用于标识这个耳标是否使用.0是未使用 1是已使用" prop="isUse">
          <el-input v-model="form.isUse" placeholder="请输入该字段用于标识这个耳标是否使用.0是未使用 1是已使用" />
        </el-form-item>
        <el-form-item label="投保id" prop="insuranceId">
          <el-input v-model="form.insuranceId" placeholder="请输入投保id" />
        </el-form-item>
        <el-form-item label="贷款id 如果=0就是没贷款，不等于0就是已贷款" prop="loans">
          <el-input v-model="form.loans" placeholder="请输入贷款id 如果=0就是没贷款，不等于0就是已贷款" />
        </el-form-item>
        <el-form-item label="地区id" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入地区id" />
        </el-form-item>
        <el-form-item label="养殖户" prop="name">
          <el-input v-model="form.name" placeholder="请输入养殖户" />
        </el-form-item>
        <el-form-item label="地区" prop="deptName">
          <el-input v-model="form.deptName" placeholder="请输入地区" />
        </el-form-item>
        <el-form-item label="是否报废1=未报费，2=已报废" prop="scrap">
          <el-input v-model="form.scrap" placeholder="请输入是否报废1=未报费，2=已报废" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTagNumber,
  getTagNumber,
  delTagNumber,
  addTagNumber,
  updateTagNumber,
  exportTagNumber, updateEarNumber, updateEar
} from '@/api/dgw/tagNumber'
import { importTemplate } from '@/api/system/user'
import { getToken } from '@/utils/auth'
import { queryDeptCun } from '@/api/system/dept'
import { listQueryVillage, queryVSum } from '@/api/dgw/registration'
import { queryEarList, querySum } from '@/api/dgw/earnumberTable'

export default {
  name: "TagNumber",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 标题
      label:'村庄(**)',
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      Sum:0,
      ESum: 0,
      // 总条数
      total: 0,
      // 耳标表格数据
      tagNumberList: [],
      deptList: [],
      deptNameList: [],
      deptNameUserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      name:null,
      names:null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        earNumber: null,
        name: null,
        deptName:null,
      },
      queryParam: {
        villagesTowns: null
      },
      queryParamUser:{
        village:null,
        villagesTowns:null,
      },
      queryParamSum:{
        deptId:null
      },
     number:{
       EarNumber:null,
       earNumber:null
     },
      queryParamEar:{
        name:null,
        deptName:null,
        phone:null
      },
      // 表单参数
      form: {},
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/dgw/tagNumber/importData'
      },
      // 表单校验
      rules: {
        earNumber: [
          { required: true, message: "耳标编号不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getQueryDeptCun(),
      this.getListSum();
  },
  methods: {
    /** 查询耳标列表 */
    getListSum(){
      queryVSum(this.queryParamUser).then(response=>{
        this.Sum = response.data.sum
      })
      querySum(this.queryParamSum).then(response=>{
        console.log("耳标总数：{}",response)
        this.ESum=response.data.sum
      })
    },
    getQueryDeptCun() {
      this.loading = true
      queryDeptCun().then(response => {
        console.log('乡镇数据', response)
        this.deptList = response.data
        this.loading = false
      })
    },
    getQueryDeptName() {
      this.loading = true
      listQueryVillage(this.queryParam).then(response => {
        this.label='村庄('+response.total+')'
        console.log('村', response)
        this.deptNameList = response.rows
        this.loading = false
      })
    },
    getList() {
      this.loading = true;
      listTagNumber(this.queryParams).then(response => {
        this.tagNumberList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        tagNumberId: null,
        earNumber: null,
        createTime: null,
        userId: null,
        phone: null,
        isUse: null,
        enterpriseId: null,
        insuranceId: null,
        loans: null,
        deptId: null,
        name: null,
        deptName: null,
        scrap: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.tagNumberId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加耳标";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const tagNumberId = row.tagNumberId || this.ids
      getTagNumber(tagNumberId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改耳标";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.tagNumberId != null) {
            updateTagNumber(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTagNumber(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const tagNumberIds = row.tagNumberId || this.ids;
      this.$modal.confirm('是否确认删除耳标编号为"' + tagNumberIds + '"的数据项？').then(function() {
        return delTagNumber(tagNumberIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$modal.confirm('是否确认导出所有耳标数据项？').then(() => {
        this.exportLoading = true
        return exportTagNumber(queryParams)
      }).then(response => {
        this.download(response.msg)
        this.exportLoading = false
      }).catch(() => {
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /*查询村*/
    getSum(row) {
      console.log("11111",row)
      this.queryParam.villagesTowns = row.deptName
      this.getQueryDeptName()
      this.queryParamSum.deptId = row.deptId
      this.queryParamUser.villagesTowns = row.deptName
      this.queryParamUser.village=null
      // this.queryParamUser.villagesTowns =row.deptName;
    },
    // 行鼠标点击事件
    selectRow(row, column, event) {
      console.log("行鼠标点击事件",row);

      this.name = row.deptName;
    },
    // 更改选中行背景色
    rowStyle({ row }) {
      if (this.name === row.deptName) {
        return { 'background-color': '#fae100', cursor: 'pointer' };
      }
      return { cursor: 'pointer' };
    },
    rowStyleU({ row }) {
      if (this.names === row.village) {
        return { 'background-color': '#fae100', cursor: 'pointer' };
      }
      return { cursor: 'pointer' };
    },
    //查询耳标编号
    ClickEar(row){
      if(row.deptId !=0){
        this.queryParamSum.deptId=row.deptId

      }else {
        this.queryParamSum.deptId=1
      }
    this.queryParams.deptName=row.village
      this.names = row.village
      this.getListSum()
     this.getList();
    },
    updateScrap(row){
      this.$confirm('此操作将销毁该耳标'+row.earNumber+', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateEarNumber(row.earNumber).then(response=>{
        })
        this.$message({
          type: 'success',
          message: '核销成功!'
        });

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消核销'
        });
      });
    },
    updateEarNumber(row){
      console.log("点击事件：",row)
      this.$prompt('请输入新的耳标号', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern:/^ZM[0-9]{9}$/,
        inputErrorMessage: '耳标格式错误 提示：开头字母ZM剩下九位为数字'
      }).then(({ value }) => {
        this.number.EarNumber=value;
        this.number.earNumber= row.earNumber;
        updateEar(this.number).then(response=>{
        })
        this.$message({
          type: 'success',
          message: '你的新耳标号: ' + value
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    }
  }
};
</script>
